// -------------------------------------------------
// BlinKit - BlinKit Library
// -------------------------------------------------
//   File Name: qjs_console.cpp
// Description: Bindings for Console
//      Author: Ziming Li
//     Created: 2022-03-04
// -------------------------------------------------
// Copyright (C) 2022 MingYang Software Technology.
// -------------------------------------------------

#include "./qjs_bindings.h"

#include "blinkit/blink/renderer/bindings/core/qjs/qjs.h"
#include "blinkit/blink/renderer/bindings/core/qjs/qjs_c_function_list_entries.h"

namespace BlinKit {
namespace qjs {

namespace Strings {
static const char Log[] = "log";
}

class Output
{
public:
    enum Type {
        Log, Error
    };

    static JSValue Impl(JSContext *ctx, JSValueConst, int argc, JSValueConst *argv, int magic)
    {
        const char *type = nullptr;
        switch (magic)
        {
            case Log:
                type = "LOG";
                break;
            case Error:
                type = "ERROR";
                break;
            default:
                ASSERT_NOT_REACHED();
                return JS_UNDEFINED;
        }

        std::string output;

        Context context(*ctx);
        for (int i = 0; i < argc; ++i)
        {
            std::string s;
            if (context.ToString(s, argv[i]))
            {
                output.append(s);
                output.push_back(' ');
            }
        }

        if (!output.empty())
            output.pop_back();

        zed::log("JS.CONSOLE.{}: {}", type, output);
        return JS_UNDEFINED;
    }
};

void AddConsole(JSContext *ctx, JSValue global)
{
    static const JSCFunctionListEntry ConsoleFuncs[] = {
        CFunctionWithMagicEntry("error", 1, Output::Impl, Output::Error),
        CFunctionWithMagicEntry(Strings::Log, 1, Output::Impl, Output::Log),
        AliasEntry("info", Strings::Log)
    };
    static const JSCFunctionListEntry GlobalFuncs[] = {
        ObjectEntry("console", ConsoleFuncs, std::size(ConsoleFuncs), JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE)
    };
    JS_SetPropertyFunctionList(ctx, global, GlobalFuncs, std::size(GlobalFuncs));
}

} // namespace qjs
} // namespace BlinKit
